/**
 * 搜索组件
 * Search Component
 */

class SearchComponent {
  constructor() {
    this.searchInput = null;
    this.searchResults = null;
    this.searchHistory = JSON.parse(localStorage.getItem('search_history') || '[]');
    this.currentQuery = '';
    this.searchTimeout = null;
    this.isSearching = false;
    this.suggestions = [];
    this.init();
  }

  /**
   * 初始化搜索组件
   */
  init() {
    this.searchInput = document.getElementById('global-search');
    if (!this.searchInput) return;

    this.createSearchDropdown();
    this.bindEvents();
  }

  /**
   * 创建搜索下拉框
   */
  createSearchDropdown() {
    const searchContainer = this.searchInput.parentElement;
    
    // 创建搜索结果下拉框
    const dropdown = document.createElement('div');
    dropdown.id = 'search-dropdown';
    dropdown.className = 'absolute top-full left-0 right-0 bg-white border border-neutral-200 rounded-lg shadow-lg mt-1 max-h-96 overflow-y-auto z-50 hidden';
    
    searchContainer.appendChild(dropdown);
    this.searchResults = dropdown;
  }

  /**
   * 绑定事件
   */
  bindEvents() {
    // 输入事件 - 实时搜索
    this.searchInput.addEventListener('input', (e) => {
      this.handleInput(e.target.value);
    });

    // 焦点事件 - 显示搜索历史
    this.searchInput.addEventListener('focus', () => {
      this.showSearchHistory();
    });

    // 键盘事件 - 处理导航和选择
    this.searchInput.addEventListener('keydown', (e) => {
      this.handleKeydown(e);
    });

    // 点击其他地方关闭搜索下拉框
    document.addEventListener('click', (e) => {
      if (!this.searchInput.contains(e.target) && !this.searchResults.contains(e.target)) {
        this.hideSearchResults();
      }
    });

    // 全局搜索快捷键 Ctrl+K
    document.addEventListener('keydown', (e) => {
      if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        this.focusSearch();
      }
    });
  }

  /**
   * 处理输入
   */
  handleInput(query) {
    this.currentQuery = query.trim();

    // 清除之前的搜索定时器
    if (this.searchTimeout) {
      clearTimeout(this.searchTimeout);
    }

    if (this.currentQuery.length === 0) {
      this.showSearchHistory();
      return;
    }

    if (this.currentQuery.length < 2) {
      this.hideSearchResults();
      return;
    }

    // 防抖搜索
    this.searchTimeout = setTimeout(() => {
      this.performSearch(this.currentQuery);
    }, 300);
  }

  /**
   * 执行搜索
   */
  async performSearch(query) {
    if (this.isSearching) return;

    try {
      this.isSearching = true;
      this.showSearchLoading();

      // 并行搜索笔记和文件
      const [notesResults, filesResults] = await Promise.all([
        this.searchNotes(query),
        this.searchFiles(query)
      ]);

      // 获取搜索建议
      const suggestions = await this.getSuggestions(query);

      this.displaySearchResults({
        query,
        notes: notesResults,
        files: filesResults,
        suggestions
      });

    } catch (error) {
      console.error('搜索失败:', error);
      this.showSearchError('搜索失败，请重试');
    } finally {
      this.isSearching = false;
    }
  }

  /**
   * 搜索笔记
   */
  async searchNotes(query) {
    try {
      const response = await api.get('/notes', {
        search: query,
        limit: 5
      });
      return response.data || [];
    } catch (error) {
      console.error('搜索笔记失败:', error);
      return [];
    }
  }

  /**
   * 搜索文件
   */
  async searchFiles(query) {
    try {
      const response = await api.get('/files', {
        search: query,
        limit: 5
      });
      return response.data || [];
    } catch (error) {
      console.error('搜索文件失败:', error);
      return [];
    }
  }

  /**
   * 获取搜索建议
   */
  async getSuggestions(query) {
    // 基于搜索历史生成建议
    const historySuggestions = this.searchHistory
      .filter(item => item.toLowerCase().includes(query.toLowerCase()))
      .slice(0, 3);

    // 基于常用关键词生成建议
    const commonKeywords = ['工作', '个人', '学习', '项目', '会议', '笔记', '文档', '图片'];
    const keywordSuggestions = commonKeywords
      .filter(keyword => keyword.includes(query))
      .slice(0, 2);

    return [...historySuggestions, ...keywordSuggestions];
  }

  /**
   * 显示搜索结果
   */
  displaySearchResults(results) {
    const { query, notes, files, suggestions } = results;
    let html = '';

    // 搜索建议
    if (suggestions.length > 0) {
      html += `
        <div class="p-3 border-b border-neutral-100">
          <div class="text-xs font-semibold text-neutral-500 uppercase tracking-wide mb-2">搜索建议</div>
          ${suggestions.map(suggestion => `
            <div class="flex items-center gap-2 p-2 rounded-md hover:bg-neutral-50 cursor-pointer search-suggestion" data-suggestion="${suggestion}">
              <i class="fa fa-search text-neutral-400"></i>
              <span class="text-sm text-neutral-700">${this.highlightQuery(suggestion, query)}</span>
            </div>
          `).join('')}
        </div>
      `;
    }

    // 笔记结果
    if (notes.length > 0) {
      html += `
        <div class="p-3 border-b border-neutral-100">
          <div class="text-xs font-semibold text-neutral-500 uppercase tracking-wide mb-2">笔记</div>
          ${notes.map(note => `
            <div class="flex items-center gap-3 p-2 rounded-md hover:bg-neutral-50 cursor-pointer search-result" data-type="note" data-id="${note.id}">
              <div class="w-8 h-8 bg-blue-100 rounded-md flex items-center justify-center flex-shrink-0">
                <i class="fa fa-sticky-note text-blue-600"></i>
              </div>
              <div class="flex-1 min-w-0">
                <p class="font-medium text-neutral-800 truncate">${this.highlightQuery(note.title, query)}</p>
                <p class="text-sm text-neutral-500 truncate">${this.highlightQuery(this.stripHtml(note.content || ''), query)}</p>
              </div>
            </div>
          `).join('')}
        </div>
      `;
    }

    // 文件结果
    if (files.length > 0) {
      html += `
        <div class="p-3 border-b border-neutral-100">
          <div class="text-xs font-semibold text-neutral-500 uppercase tracking-wide mb-2">文件</div>
          ${files.map(file => `
            <div class="flex items-center gap-3 p-2 rounded-md hover:bg-neutral-50 cursor-pointer search-result" data-type="file" data-id="${file.id}">
              <div class="w-8 h-8 bg-green-100 rounded-md flex items-center justify-center flex-shrink-0">
                <i class="fa ${this.getFileIcon(file.file_type)} text-green-600"></i>
              </div>
              <div class="flex-1 min-w-0">
                <p class="font-medium text-neutral-800 truncate">${this.highlightQuery(file.original_name, query)}</p>
                <p class="text-sm text-neutral-500">${this.formatFileSize(file.file_size)} • ${this.formatDate(file.created_at)}</p>
              </div>
            </div>
          `).join('')}
        </div>
      `;
    }

    // 查看全部结果
    if (notes.length > 0 || files.length > 0) {
      html += `
        <div class="p-3">
          <button class="w-full text-left p-2 rounded-md hover:bg-neutral-50 text-primary font-medium search-view-all" data-query="${query}">
            <i class="fa fa-search mr-2"></i>
            查看"${query}"的全部结果
          </button>
        </div>
      `;
    }

    // 无结果
    if (notes.length === 0 && files.length === 0 && suggestions.length === 0) {
      html = `
        <div class="p-6 text-center text-neutral-500">
          <i class="fa fa-search text-2xl mb-2"></i>
          <p>未找到相关结果</p>
          <p class="text-sm mt-1">尝试使用不同的关键词</p>
        </div>
      `;
    }

    this.searchResults.innerHTML = html;
    this.showSearchResults();
    this.bindSearchResultEvents();
  }

  /**
   * 绑定搜索结果事件
   */
  bindSearchResultEvents() {
    // 搜索建议点击
    const suggestions = this.searchResults.querySelectorAll('.search-suggestion');
    suggestions.forEach(item => {
      item.addEventListener('click', () => {
        const suggestion = item.dataset.suggestion;
        this.searchInput.value = suggestion;
        this.handleInput(suggestion);
      });
    });

    // 搜索结果点击
    const results = this.searchResults.querySelectorAll('.search-result');
    results.forEach(item => {
      item.addEventListener('click', () => {
        const type = item.dataset.type;
        const id = item.dataset.id;
        this.openSearchResult(type, id);
      });
    });

    // 查看全部结果
    const viewAllBtn = this.searchResults.querySelector('.search-view-all');
    if (viewAllBtn) {
      viewAllBtn.addEventListener('click', () => {
        const query = viewAllBtn.dataset.query;
        this.showFullSearchResults(query);
      });
    }
  }

  /**
   * 显示搜索历史
   */
  showSearchHistory() {
    if (this.searchHistory.length === 0) {
      this.hideSearchResults();
      return;
    }

    const html = `
      <div class="p-3">
        <div class="flex items-center justify-between mb-2">
          <div class="text-xs font-semibold text-neutral-500 uppercase tracking-wide">搜索历史</div>
          <button class="text-xs text-neutral-400 hover:text-neutral-600" id="clear-search-history">清除</button>
        </div>
        ${this.searchHistory.slice(0, 5).map(item => `
          <div class="flex items-center gap-2 p-2 rounded-md hover:bg-neutral-50 cursor-pointer search-history-item" data-query="${item}">
            <i class="fa fa-history text-neutral-400"></i>
            <span class="text-sm text-neutral-700 flex-1">${item}</span>
            <button class="text-neutral-300 hover:text-neutral-500 remove-history-item" data-query="${item}">
              <i class="fa fa-times"></i>
            </button>
          </div>
        `).join('')}
      </div>
    `;

    this.searchResults.innerHTML = html;
    this.showSearchResults();

    // 绑定历史记录事件
    this.bindHistoryEvents();
  }

  /**
   * 绑定历史记录事件
   */
  bindHistoryEvents() {
    // 点击历史记录项
    const historyItems = this.searchResults.querySelectorAll('.search-history-item');
    historyItems.forEach(item => {
      item.addEventListener('click', (e) => {
        if (e.target.closest('.remove-history-item')) return;
        const query = item.dataset.query;
        this.searchInput.value = query;
        this.handleInput(query);
      });
    });

    // 删除单个历史记录
    const removeButtons = this.searchResults.querySelectorAll('.remove-history-item');
    removeButtons.forEach(btn => {
      btn.addEventListener('click', (e) => {
        e.stopPropagation();
        const query = btn.dataset.query;
        this.removeFromHistory(query);
      });
    });

    // 清除所有历史记录
    const clearBtn = this.searchResults.querySelector('#clear-search-history');
    if (clearBtn) {
      clearBtn.addEventListener('click', () => {
        this.clearSearchHistory();
      });
    }
  }

  /**
   * 显示搜索加载状态
   */
  showSearchLoading() {
    this.searchResults.innerHTML = `
      <div class="p-6 text-center text-neutral-500">
        <i class="fa fa-spinner fa-spin text-2xl mb-2"></i>
        <p>搜索中...</p>
      </div>
    `;
    this.showSearchResults();
  }

  /**
   * 显示搜索错误
   */
  showSearchError(message) {
    this.searchResults.innerHTML = `
      <div class="p-6 text-center text-neutral-500">
        <i class="fa fa-exclamation-triangle text-2xl mb-2 text-red-500"></i>
        <p>${message}</p>
      </div>
    `;
    this.showSearchResults();
  }

  /**
   * 显示搜索结果
   */
  showSearchResults() {
    this.searchResults.classList.remove('hidden');
  }

  /**
   * 隐藏搜索结果
   */
  hideSearchResults() {
    this.searchResults.classList.add('hidden');
  }

  /**
   * 聚焦搜索框
   */
  focusSearch() {
    this.searchInput.focus();
    this.searchInput.select();
  }

  /**
   * 处理键盘导航
   */
  handleKeydown(e) {
    if (e.key === 'Escape') {
      this.hideSearchResults();
      this.searchInput.blur();
    } else if (e.key === 'Enter') {
      e.preventDefault();
      if (this.currentQuery) {
        this.addToHistory(this.currentQuery);
        this.showFullSearchResults(this.currentQuery);
      }
    }
  }

  /**
   * 打开搜索结果
   */
  openSearchResult(type, id) {
    this.addToHistory(this.currentQuery);
    this.hideSearchResults();

    if (type === 'note') {
      // TODO: 打开笔记详情
      console.log('打开笔记:', id);
      notification.info(`打开笔记 ${id}`);
    } else if (type === 'file') {
      // TODO: 打开文件详情
      console.log('打开文件:', id);
      notification.info(`打开文件 ${id}`);
    }
  }

  /**
   * 显示完整搜索结果页面
   */
  showFullSearchResults(query) {
    this.addToHistory(query);
    this.hideSearchResults();
    
    // TODO: 实现完整搜索结果页面
    console.log('显示完整搜索结果:', query);
    notification.info(`搜索: ${query}`);
  }

  /**
   * 添加到搜索历史
   */
  addToHistory(query) {
    if (!query || query.length < 2) return;

    // 移除重复项
    this.searchHistory = this.searchHistory.filter(item => item !== query);
    
    // 添加到开头
    this.searchHistory.unshift(query);
    
    // 限制历史记录数量
    this.searchHistory = this.searchHistory.slice(0, 10);
    
    // 保存到本地存储
    localStorage.setItem('search_history', JSON.stringify(this.searchHistory));
  }

  /**
   * 从历史记录中移除
   */
  removeFromHistory(query) {
    this.searchHistory = this.searchHistory.filter(item => item !== query);
    localStorage.setItem('search_history', JSON.stringify(this.searchHistory));
    this.showSearchHistory();
  }

  /**
   * 清除搜索历史
   */
  clearSearchHistory() {
    this.searchHistory = [];
    localStorage.removeItem('search_history');
    this.hideSearchResults();
  }

  /**
   * 高亮查询关键词
   */
  highlightQuery(text, query) {
    if (!query || !text) return text;
    
    const regex = new RegExp(`(${query})`, 'gi');
    return text.replace(regex, '<mark class="bg-yellow-200 px-1 rounded">$1</mark>');
  }

  /**
   * 去除HTML标签
   */
  stripHtml(html) {
    const tmp = document.createElement('div');
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText || '';
  }

  /**
   * 获取文件图标
   */
  getFileIcon(fileType) {
    const icons = {
      image: 'fa-image',
      video: 'fa-video-camera',
      audio: 'fa-music',
      document: 'fa-file-text',
      other: 'fa-file'
    };
    return icons[fileType] || icons.other;
  }

  /**
   * 格式化文件大小
   */
  formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  /**
   * 格式化日期
   */
  formatDate(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (days === 0) return '今天';
    if (days === 1) return '昨天';
    if (days < 7) return `${days}天前`;
    return date.toLocaleDateString();
  }

  /**
   * 清除搜索
   */
  clearSearch() {
    this.searchInput.value = '';
    this.currentQuery = '';
    this.hideSearchResults();
  }

  /**
   * 获取当前搜索查询
   */
  getCurrentQuery() {
    return this.currentQuery;
  }

  /**
   * 获取搜索历史
   */
  getSearchHistory() {
    return [...this.searchHistory];
  }
}

// 导出搜索组件
window.SearchComponent = SearchComponent;